﻿using UnityEngine;

namespace GameToolkit
{
    [CreateAssetMenu(fileName = "InputAxisDescriptor", menuName = "角色控制/标量输入描述")]
    public class InputAxisDescriptor : InputDescriptor
    {
        [Header("From GameInput")]
        [SerializeField, GameAxis]
        string m_AxisName;

        [Header("From Computer")]
        [SerializeField, Range(0.01f, 1f)]
        float m_Threshold = 0.1f;

        GameInput.IAxis mAxis;

        public override ActorBehaviour.IInputAction Create(bool fromGameInput)
        {
            if (fromGameInput)
            {
                if (mAxis == null)
                    mAxis = string.IsNullOrEmpty(m_AxisName) ? null : GameInput.GetAxis(m_AxisName, true);
#if UNITY_EDITOR
                if (mAxis == null)
                    Debug.LogWarning($"The input({m_AxisName}) is not exists.", this);
#endif
                return new ActionFromGinput(mAxis);
            }
            else
            {
                return new ActionFromDesc(this);
            }
        }

        class ActionFromGinput : ActorBehaviour.IInputAction<float>
        {
            GameInput.IAxis mAxis;
            public ActionFromGinput(GameInput.IAxis axis)
            {
                mAxis = axis;
            }

            public bool IsHolding => mAxis != null && mAxis.HasButton;

            public float GetInputValue()
            {
                return mAxis.Value;
            }
        }

        class ActionFromDesc : IConfigurableInputAction<float>
        {
            InputAxisDescriptor mDesc;
            float mAxisValue;

            public void SetValue(float axis)
            {
                mAxisValue = axis;
            }

            public ActionFromDesc(InputAxisDescriptor desc)
            {
                mDesc = desc;
            }

            public bool IsHolding => mDesc != null && Mathf.Abs(mAxisValue) >= mDesc.m_Threshold;

            public float GetInputValue()
            {
                return mAxisValue;
            }
        }
    }
}
